// 实现这个项目的构建任务
const { src, dest, parallel, series } = require('gulp')

const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
// const plugins.sass = require('gulp-sass')
// const plugins.babel = require('gulp-babel')
// const plugins.swig = require('gulp-swig')
// const plugins.imagemin = require('gulp-imagemin')

const del = require('del')

const browserSync = require('browser-sync')
const { watch, reload } = require('browser-sync')
const bs = browserSync.create()

const data = {
  pkg: require('./package.json'),
  date: new Date(),
  menus: [],
}

const clean = () => del(['dist', 'temp'])

const page = () =>
  src('src/**/*.html', { base: 'src' })
    .pipe(plugins.swig({ data }))
    .pipe(dest('temp'))

const style = () =>
  src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'))

const script = () =>
  src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))

const image = () =>
  src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))

const font = () =>
  src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))

const extra = () =>
  src('public/**', { base: 'src' }).pipe(dest('dist'))

const serve = () => {
  watch('src/**/*.html', page)
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  // watch('src/assets/images/**', image)
  // watch('src/assets/fonts/**', font)
  // watch('public/**', extra)
  watch(
    ['src/assets/images/**', 'src/assets/fonts/**', 'public/**'],
    bs.reload
  )

  bs.init({
    // notify: false,
    // port: 7000,
    // open: false,
    files: 'dist/**',
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules',
      },
    },
  })
}

const useref = () =>
  src('dist/*.html', { base: 'dist' })
    .pipe(plugins.useref({ searchPath: ['dist', '.'] }))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(
      plugins.if(
        /\.html$/,
        plugins.htmlmin({
          collapseWhitespace: true,
          minifyCSS: true,
          minifyJS: true,
        })
      )
    )
    .pipe(dest('dist'))

const compile = parallel(page, style, script)

const build = series(
  clean,
  compile,
  useref,
  parallel(image, font, extra)
)

const develop = series(compile, serve)

module.exports = {
  clean,
  serve,
  build,
  develop,
}
